/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.ekuma.data.dao;

import cn.ekuma.data.dao.bean.CompositeKey;
import cn.ekuma.data.dao.bean.IKeyed;

import com.openbravo.data.basic.BasicException;
import com.openbravo.data.loader.DataWrite;
import com.openbravo.data.loader.I_Session;
import com.openbravo.data.loader.PreparedSentence;
import com.openbravo.data.loader.SentenceFind;
import com.openbravo.data.loader.SerializerWrite;
import com.openbravo.data.loader.Session;
import java.util.List;

/**
 *
 * @author Administrator
 */
public abstract class KeyedViewDAO<T,K> extends ViewDAO<T> implements IKeyed<K>{
    private SentenceFind findSentence;

    public KeyedViewDAO(I_Session s) {
        super(s);
    }

     public T find(IKeyed id) throws BasicException {
        return (T) getFindSentence().find(id);
    }

    public  SentenceFind getFindSentence() {
        if (findSentence == null) {
            findSentence = new PreparedSentence(s, getFindSQL(), getKeySerializerWrite(),  this);
        }
        return findSentence;
    }

    public SerializerWrite<IKeyed> getKeySerializerWrite() {
        return new SerializerWrite<IKeyed>() {
            public void writeValues(DataWrite dp, IKeyed obj) throws BasicException {
                Object value = obj.getKey();
                if (value instanceof String) {
                    dp.setString(1, (String) value);
                } else if (value instanceof Integer) {
                    dp.setInt(1, (Integer) value);
                } else if (value instanceof CompositeKey) {
                    CompositeKey compositeKey = (CompositeKey) obj.getKey();
                    for (int i = 1; i < compositeKey.size()+1; i++) {
                        value = compositeKey.getKey(i).getKey();
                        if (value instanceof String) {
                            dp.setString(i, (String) value);
                        } else if (value instanceof Integer) {
                            dp.setInt(i, (Integer) value);
                        }
                    }
                }
            }
        };
    }

    public abstract String getFindSQL();

    public abstract String getListSQL();

    public abstract String getListParentSql();
    
    public List list(I_ParentNode parent) throws BasicException {
        return  (List) new PreparedSentence(s, getListParentSql(), getKeySerializerWrite(), this).list();
    }
}
